package cn.hl.hm.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.vizhuo.smscode.model.SMSCode;

import cn.hl.hm.constants.UploadConfig;
import cn.hl.hm.constants.UserStatus;
import cn.hl.hm.entity.Order;
import cn.hl.hm.entity.Push;
import cn.hl.hm.entity.User;
import cn.hl.hm.entity.UserRoute;
import cn.hl.hm.entity.backstage.BackStageMenus;
import cn.hl.hm.entity.backstage.BackStageRoleMenu;
import cn.hl.hm.entity.backstage.BackStageRoles;
import cn.hl.hm.entity.backstage.TBackstageUserBean;
import cn.hl.hm.service.BackstageAuthService;
import cn.hl.hm.service.BackstageOperationRecordService;
import cn.hl.hm.service.OrderService;
import cn.hl.hm.service.PushToAppIService;
import cn.hl.hm.service.SMSCodeIService;
import cn.hl.hm.service.TBackstageUserService;
import cn.hl.hm.service.UserService;
import cn.hl.hm.util.AppPager;
import cn.hl.hm.util.BeanPicUtil;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.MD5Util;
import cn.hl.hm.util.NumberUtils;
import cn.hl.hm.util.Result;
import cn.hl.hm.util.TokenProcessor;
import smsClient.TestSDKClient;

@Controller
@RequestMapping("/userController")
public class UserController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    SMSCodeIService sMSCodeIService;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
	@Qualifier("pushToAppServiceImpl")
	private PushToAppIService pushToAppIService;
    @Autowired
    TBackstageUserService tBackstageUserService;
    @Autowired
    BackstageAuthService backstageAuthService;
    @Autowired
	@Qualifier("uploadConfig")
	private UploadConfig uploadConfig;
    
    @Autowired
    private BeanPicUtil beanPicUtil;
    
    @Autowired
    BackstageOperationRecordService operationRecordService;
    	/**
	  * @Title: login  
	  * @Description: 用户登录
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param pass
	  * @param appId
	  * @param request
	  * @param response
	  * @throws IOException void 
	  * @throws
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam String userAccount,
            @RequestParam String password,
            String appId,
            String deviceToken ,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---登录方法---userController/login");
		request.setCharacterEncoding("UTF-8");
		User record = new User();
		record.setUserAccount(userAccount);
		record.setPassword(password);
		/*if(StringUtils.isNotBlank(appId)){
			record.setPlatformId(appId);
		}*/
		try{
			List<User> selectUser = userService.selectUser(record);
			if (null != selectUser&&selectUser.size()>0) {// 登录
				User result = selectUser.get(0);
				// 登录
				request.getSession().setAttribute("LOGIN_USER_ACCOUNT", result.getUserAccount());
				request.getSession(false).setAttribute("USER_SECURITY_TOKEN", result.getDeviceToken());
				//用户登录活跃统计 

				// 更改操作时间
				User u = new User();
				u.setUpdateTime(new Date());
				u.setId(result.getId());
				if(StringUtils.isNoneBlank(deviceToken)){
					u.setDeviceToken(deviceToken);
				}
			    userService.updateUser(u);
			    record.setPassword(null);
				Result.ok(result, InfoCode.SUCCESS, response);
				try {
					userService.addHotRecord(result.getId(), "1", "1");
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;

			} else {
				Result.ok(null, InfoCode.AUTH_ERROR, response);
				return null;

			}
		}catch(Exception e){
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		
	}
	/**
	  * @Title: checkMsg  
	  * @Description: 忘记密码验证 验证码
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param verifyCode
	  * @param appId
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/checktMsgCode", method = RequestMethod.POST)
	public String checkMsg(@RequestParam String userAccount,
           @RequestParam String verifyCode,
           @RequestParam String appId,
           @RequestParam String type,// 3 找回密码
           HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---忘记密码验证---userController/checktMsgCode");
		request.setCharacterEncoding("UTF-8");
		User record = new User();
		record.setUserAccount(userAccount);
		try {

			if (type.equals("3")) {
				List<User> selectUser = userService.selectUser(record);
				if (null != selectUser && selectUser.size() > 0) {
					SMSCode sMSCode = new SMSCode();
					sMSCode.setMobile(userAccount);
					sMSCode.setCode(verifyCode);
					SMSCode smsCode = sMSCodeIService.findCode(sMSCode);
					if (smsCode == null) {
						Result.ok(null, InfoCode.MESSAGE_ERROR, response);
						return null;
					}
					//用户存在且验证码正确
					Result.ok(null, InfoCode.SUCCESS, response);
					return null;
				} else {
					Result.ok(null, InfoCode.RESET_ERROR, response);
					return null;

				}
			}

		}catch(Exception e){
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		return null;
		
	}
	/**
	  * @Title: reset  
	  * @Description: 忘记密码（重置）
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param password
	  * @param appId
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/forget", method = RequestMethod.POST)
	public String reset(@RequestParam String userAccount,
            @RequestParam String password,
            @RequestParam String appId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---忘记密码重置（先调用接口3）---userController/forget");
		request.setCharacterEncoding("UTF-8");
		User record = new User();
		record.setUserAccount(userAccount);
		try{
			List<User> selectUser = userService.selectUser(record);
			if (null != selectUser&&selectUser.size()>0) {// 登录
				User result = selectUser.get(0);
					result.setUpdateTime(new Date());
					result.setPassword(password);
					if(StringUtils.isNotBlank(appId)){
						result.setPlatformId(appId);
					}
					int updateUser = userService.updateUser(result);
					if(updateUser>0){
						result.setPassword(null);
						Result.ok(result, InfoCode.SUCCESS, response);
						return null;
					}else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}
			} else {
				Result.ok(null, InfoCode.RESET_ERROR, response);
				return null;

			}
		}catch(Exception e){
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		
	}
	
	/**
	  * @Title: loginout  
	  * @Description: 退出
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param appId
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/loginout", method = RequestMethod.POST)
	public String loginout(@RequestParam String userAccount,
            @RequestParam String appId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---退出登录---userController/loginout");
		request.setCharacterEncoding("UTF-8");
		User record = new User();
		record.setUserAccount(userAccount);
		try {
			request.getSession().removeAttribute("LOGIN_USER_ACCOUNT");
			request.getSession(false).removeAttribute("USER_SECURITY_TOKEN");
			Result.ok(null, InfoCode.SUCCESS, response);
			return null;
		}catch(Exception e){
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	  * @Title: updatePass  
	  * @Description: 修改密码
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param oldPass
	  * @param newPass
	  * @param appId
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/updatePass", method = RequestMethod.POST)
	public String updatePass(@RequestParam String userAccount,
            @RequestParam String oldPass,
            @RequestParam String newPass,
            @RequestParam String appId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---修改密码---userController/updatePass");
		request.setCharacterEncoding("UTF-8");
		User record = new User();
		record.setUserAccount(userAccount);
		record.setPassword(oldPass);

		try{
			List<User> selectUser = userService.selectUser(record);
			if (null != selectUser&&selectUser.size()>0) {
				User result = selectUser.get(0);
					result.setUpdateTime(new Date());
					result.setPassword(newPass);
					if(StringUtils.isNotBlank(appId)){
						result.setPlatformId(appId);
					}
					int updateUser = userService.updateUser(result);
					if(updateUser>0){
						Result.ok(result, InfoCode.SUCCESS, response);
						return null;
					}else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}
			} else {
				Result.ok(null, InfoCode.AUTH_ERROR, response);
				return null;

			}
		}catch(Exception e){
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		
	}
	
	/**
	  * @Title: regist  
	  * @Description: 注册
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param verifyCode
	  * @param appId
	  * @param password
	  * @param invitationCode
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public String regist(@RequestParam String userAccount,
            @RequestParam String verifyCode,
            String appId,
            @RequestParam String password,
            String deviceToken,//推送
            String invitationCode,//邀请码 预留
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户---注册方法---userController/regist");
		request.setCharacterEncoding("UTF-8");
		if (StringUtils.isNotBlank(invitationCode)) {
			// 预留功能
		}
		// 1 验证码
		SMSCode sMSCode = new SMSCode();
		sMSCode.setMobile(userAccount);
		sMSCode.setCode(verifyCode);
		try {
			SMSCode smsCode = sMSCodeIService.findCode(sMSCode);
			if (smsCode == null) {
				Result.ok(null, InfoCode.MESSAGE_ERROR, response);
				return null;
			}
			// 是否重复注册
			User param = new User();
			param.setUserAccount(userAccount);
			List<User> selectUser = userService.selectUser(param);
			if (selectUser != null&&selectUser.size()>0) {
				Result.ok(null, InfoCode.REGIST_ERROR, response);
				return null;
			}

			User record = new User();
			if(StringUtils.isNotBlank(appId)){
				record.setPlatformId(appId);
			}			
			record.setPassword(password);
			record.setUserAccount(userAccount);
			record.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
			if(StringUtils.isNoneBlank(deviceToken)){
				record.setDeviceToken(deviceToken);
			}			
			record.setUserStatus(UserStatus.TO_SUBMIT.getStatus());
			record.setCreateTime(new Date());
			record.setUpdateTime(new Date());
			int add = userService.add(record);
			if (add > 0) {
				// 用户注册活跃统计
				request.getSession().setAttribute("LOGIN_USER_ACCOUNT", record.getUserAccount());
				request.getSession(false).setAttribute("USER_SECURITY_TOKEN", record.getDeviceToken());
				userService.addHotRecord(record.getId(), "1", "2");
				record.setPassword(null);
				Result.ok(record, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	
	
	/**
	  * @Title: updateInfo  
	  * @Description: 更新用户信息
	  * @date: 2017年1月3日
	  * @author: 大和
	  * @param userAccount
	  * @param appId
	  * @param user
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
	public String updateInfo(@RequestParam String userAccount,
            String appId,
            User user,
            @RequestParam String userStatus,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("个人中心---更改用户信息---userController/updateInfo");
		request.setCharacterEncoding("UTF-8");
		if (user == null) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}
		if(userStatus.equals(UserStatus.UNPASS.getStatus())&&StringUtils.isBlank(user.getUserUnpassReason())){
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}
		
		try {
			user = beanPicUtil.cutUrl(user);
			User param = new User();
			param.setUserAccount(userAccount);
			List<User> selectUser = userService.selectUser(param);
			if (selectUser != null && selectUser.size() > 0) {
				User result = selectUser.get(0);
				user.setId(result.getId());
				user.setUpdateTime(new Date());
				user.setUserStatus(userStatus);
				if(StringUtils.isNotBlank(appId)){
					user.setPlatformId(appId);
				}
				int update = userService.updateUser(user);
				if (update > 0) {
					if(userStatus.equals(UserStatus.PASS.getStatus())){
						User userParam3 = new User();
						userParam3.setUserAccount(userAccount);
						List<User> selectUser2 = userService.selectUser(userParam3);
						if(selectUser2!=null&&selectUser2.size()>0){
							User user2 = selectUser.get(0);
							
							if (StringUtils.isNotBlank(user2.getDeviceToken())) {
								Push push = new Push();
								push.setPtype(3);
								push.setPushoid("");
								push.setContext("恭喜您，资料已审核成功，马上发单吧");// 要发送的内容
								push.setDisplayType("notification");// message: 消息，通知：notification
								push.setOperationType(2);// 用户类型：1司机，2发货端
								push.setPushClient("consignerPushClient");// 使用的推送Client
																			// 是往发货端：consignerPushClient
																			// 或
																			// 司机端发送：driverPushClient。
								push.setPushType("listcast");// unicast：单播 // listcast：列表
								push.setTitle("资料审核通过"); // 发送的标题
								push.setTokenStr(new String[] { user2.getDeviceToken() }); // 要发送手机的token
								// ios & android推送公共调用方法
								pushToAppIService.pushCommon(push);
								
							}
							}
					}
					
					
					
					Result.ok(null, InfoCode.SUCCESS, response);

				} else {
					Result.ok(null, InfoCode.FAILURE, response);

				}
				return null;
			} else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	
	/**
	  * @Title: selectInfo  
	  * @Description: 查询用户信息
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param userAccount
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/selectInfo", method = RequestMethod.POST)
	public String selectInfo(@RequestParam String userAccount,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("个人中心---获取用户信息---userController/selectInfo");
		request.setCharacterEncoding("UTF-8");
		try {
			User param = new User();
			param.setUserAccount(userAccount);
			List<User> selectUser = userService.selectUser(param);
			if(selectUser!=null&&selectUser.size()>0){
				User data = selectUser.get(0);
				User modifyUrl = beanPicUtil.modifyUrl(data);
				modifyUrl.setPassword(null);
				Result.ok(modifyUrl, InfoCode.SUCCESS, response);
				return null;
			}else {
				Result.ok(null, InfoCode.FAILURE, response);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;

		}
	}
	/**
	  * @Title: userList  
	  * @Description: 条件查询用户
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param userAccount
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/userList", method = RequestMethod.POST)
	public String userList(User user,
			@RequestParam Integer pageId,
			@RequestParam Integer pageCount,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户（发货人）管理---查询用户信息(列表/详情)---userController/userList");
		request.setCharacterEncoding("UTF-8");
		try {
			AppPager handle = AppPager.handle(pageId, pageCount);
			user.setPageId(handle.getPageId());
			user.setPageCount(handle.getPageCount());
			List<User> selectUser = userService.selectUser(user);
			List<User> result = new ArrayList<User>();
			if(selectUser!=null&&selectUser.size()>0){
				for (User user2 : selectUser) {
					Order param =new Order();
					param.setSenderPhone(user2.getUserAccount());
					Order order = orderService.selectUserSuccess(param);
					user2.setSuccessOrder(order.getId());
					user2.setSuccessOrderPrice(order.getTotalPrice());
					User modifyUrl = beanPicUtil.modifyUrl(user2);
					result.add(modifyUrl);
				}
			}
			Result.ok(result, InfoCode.SUCCESS, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;

		}
	}
	
	
	/**
	  * @Title: updateDeviceToken  
	  * @Description: 更新用户token
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param userAccount
	  * @param deviceToken
	  * @param appId
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/updateDeviceToken", method = RequestMethod.POST)
	public String updateDeviceToken(@RequestParam String userAccount,
			@RequestParam String deviceToken,//推送
			String appId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		   try{ 
		   request.setCharacterEncoding("UTF-8");
			User param = new User();
			param.setUserAccount(userAccount);
			List<User> selectUser = userService.selectUser(param);
			if (selectUser == null) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

			User record = new User();
			if(StringUtils.isNotBlank(appId)){
				record.setPlatformId(appId);
			}			
			record.setUserAccount(userAccount);
			if(StringUtils.isNoneBlank(deviceToken)){
				record.setDeviceToken(deviceToken);
			}	
			record.setId(selectUser.get(0).getId());
			record.setUpdateTime(new Date());
			int add = userService.updateUser(record);
			if (add > 0) {
				Result.ok(null, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);

			}
		} catch (Exception e) {
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	
	/**
	  * @Title: userRouteList  
	  * @Description: 用户常用路线列表
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param userAccount
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/userRouteList", method = RequestMethod.POST)
	public String userRouteList(@RequestParam String userAccount,
			@RequestParam Integer pageId,
			@RequestParam Integer pageCount,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户（发货人）管理---查询用户路线---userController/userRouteList");
		   try{
			   UserRoute param =new UserRoute();

			   AppPager handle = AppPager.handle(pageId, pageCount);
			   param.setPageId(handle.getPageId());
			   param.setPageCount(handle.getPageCount());
			   param.setUserAccount(userAccount);
			   List<UserRoute> selectUserRoute = userService.selectUserRoute(param);
			   Result.ok(selectUserRoute, InfoCode.SUCCESS, response);
		   } catch (Exception e) {
			   e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	/**
	 * 
	  * @Title: addUserRoute  
	  * @Description: 添加用户路线
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param userAccount
	  * @param srcAddress
	  * @param destAddress
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/addUserRoute", method = RequestMethod.POST)
	public String addUserRoute(
			@RequestParam String userAccount,
			@RequestParam String srcAddress,
			@RequestParam String destAddress,
			@RequestParam Integer operId,
			HttpServletRequest request, 
			HttpServletResponse response)
					throws IOException {
		logger.info("用户（发货人）管理---添加用户路线---userController/addUserRoute");
		try {
			UserRoute param = new UserRoute();
			param.setUserAccount(userAccount);
			param.setSrcAddress(srcAddress);
			param.setDestAddress(destAddress);
			param.setCreateTime(new Date());
			int addUserRoute = userService.addUserRoute(param);
			if (addUserRoute > 0) {
				operationRecordService.insertSelective(operId,"" , "添加用户路线：用户userAccount"+userAccount);

				Result.ok(param, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);
			}
		} catch (Exception e) {
			e.printStackTrace();

			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	/**
	 * 
	  * @Title: backstageSignIn  
	  * @Description: 管理平台 登录
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param mailbox
	  * @param passWord
	  * @param request
	  * @param response
	  * @return String 
	  * @throws
	 */
	@RequestMapping(value = "/backstageSignIn", method = RequestMethod.POST)
	public @ResponseBody String backstageSignIn(@RequestParam("mailbox") String mailbox,
			@RequestParam("passWord") String passWord, HttpServletRequest request, HttpServletResponse response) {
		logger.info("后台用户登录：start passWord" + passWord + "mailbox" + mailbox);
		try {
			TBackstageUserBean tbub = tBackstageUserService.backstageSignIn(mailbox, passWord);
			if(tbub==null){
				Result.ok(null, InfoCode.FAILURE, response);
				return null;
			}
			//权限
//			BackStageRoleMenu rm = new BackStageRoleMenu();
//			rm.setRoleId(tbub.gettBackstageUserEntity().getJurisdiction());
//			List<BackStageRoleMenu> selectUserAuths = backstageAuthService.selectInfo(rm);
//			tbub.setRoleAuthList(selectUserAuths);
			request.getSession().setAttribute("BACKSTAGEUSER", tbub);
			operationRecordService.insertSelective(tbub.gettBackstageUserEntity().getId(),tbub.gettBackstageUserEntity().getMailbox() , "登录");
			Result.ok(request.getSession().getAttribute("BACKSTAGEUSER"), InfoCode.SUCCESS, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	/**
	  * @Title: backstageSignOut  
	  * @Description: 管理平台 退出
	  * @date: 2017年1月6日
	  * @author:大和
	  * @param request
	  * @param response
	  * @return String 
	  * @throws
	 */
	@RequestMapping(value = "/backstageSignOut", method = RequestMethod.POST)
	public @ResponseBody String backstageSignOut(HttpServletRequest request, HttpServletResponse response) {
		logger.info("用户（运营）管理---退出---userController/backstageSignOut");
		try {
			request.getSession().removeAttribute("BACKSTAGEUSER");
			Result.ok(null, InfoCode.SUCCESS, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	/**
	  * @Title: addUser  
	  * @Description: 管理平台添加发货人
	  * @date: 2017年1月11日
	  * @author:大和
	  * @param userAccount
	  * @param accountType
	  * @param userName
	  * @param companyName
	  * @param request
	  * @param response
	  * @return
	  * @throws IOException String 
	  * @throws
	 */
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public String addUser(@RequestParam String userAccount,
            @RequestParam String accountType,
            @RequestParam String userName,
            @RequestParam String companyName,
            @RequestParam Integer operId,
            @RequestParam String sex,
            @RequestParam String businessLicencePic,
            @RequestParam String idCardFrontPic,
            @RequestParam String idCard,
            @RequestParam String businessLicenceNumber,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("用户（发货人）管理---添加用户---userController/addUser");
		request.setCharacterEncoding("UTF-8");
		try {
			// 是否重复注册
			User param = new User();
			param.setUserAccount(userAccount);
			List<User> selectUser = userService.selectUser(param);
			if (selectUser != null&&selectUser.size()>0) {
				Result.ok(null, InfoCode.REGIST_ERROR, response);
				return null;
			}

			User record = new User();
			String pass = NumberUtils.getRandomNumber(6);
			record.setPassword(MD5Util.MD5Encode(MD5Util.MD5Encode(pass, "UTF-8"), "UTF-8"));
			record.setName(userName);
			record.setAccountType(accountType);
			record.setUserAccount(userAccount);
			record.setOurSecurityToken(TokenProcessor.getInstance().generateToken());
			record.setUserStatus(UserStatus.PASS.getStatus());
			record.setCreateTime(new Date());
			record.setUpdateTime(new Date());
			record.setCompanyName(companyName);
			record.setSex(sex);
			record.setBusinessLicenceNumber(businessLicenceNumber);
			record.setBusinessLicencePic(businessLicencePic);
			record.setIdCard(idCard);
			record.setIdCardFrontPic(idCardFrontPic);
			
			User cutUrl = beanPicUtil.cutUrl(record);
			int add = userService.add(cutUrl);
			if (add > 0) {
				// 用户注册活跃统计
				request.getSession().setAttribute("LOGIN_USER_ACCOUNT", record.getUserAccount());
				request.getSession(false).setAttribute("USER_SECURITY_TOKEN", record.getDeviceToken());
				userService.addHotRecord(record.getId(), "1", "2");
				record.setPassword(null);
				//发短信
				//TestSDKClient.testSendSMSE(record.getUserAccount(), "【华凌叮当到】" + "恭喜您注册成功 ！ 用户名为："+record.getUserAccount()+"   密码为： "+pass+"，请勿向任何人泄露。");
				
				SendSmsRequest smsRequest = new SendSmsRequest();
				smsRequest.setTemplateParam("{\"userAccount\":\""+record.getUserAccount()+"\",\"pass\":\""+record.getUserAccount()+"\"}");
			    TestSDKClient.sendSmsByAli("SMS_110395052",smsRequest,record.getUserAccount(),"华凌叮当到");
				
				
				operationRecordService.insertSelective(operId, record.getUserAccount(), "添加发货用户姓名： "+userName+" 添加发货用户电话 "+record.getUserAccount());
				Result.ok(record, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);

			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	
}
